package interfaces.superWidgets;

import interfaces.GUISource;
import interfaces.WordWrapHelper;

import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedList;

import org.fenggui.StandardWidget;
import org.fenggui.binding.render.ImageFont;
import org.fenggui.util.Color;

public class FlowContent extends StaticContent {
	
	protected LinkedList<StandardWidget> widgets;
	protected int widgetHeight;
	protected boolean up;
	
	public FlowContent(int width, int height, int x, int y, int widgetHeight) {
		this(width, height, x, y, widgetHeight, true);
	}
	
	public FlowContent(int width, int height, int x, int y, int widgetHeight, boolean up) {
		super(width, height, x, y);
		this.widgetHeight = widgetHeight;
		this.up = up;
		
		widgets = new LinkedList<StandardWidget>();
	}
	
	public void addText(String text, Color color, ImageFont font) {
		InterfaceLabel label = new InterfaceLabel(font);
		label.setWidth(getWidth());
		WordWrapHelper.wrapWords(label, text);
		
		String[] parts = label.getText().split("\n");
		if(parts.length > 1) {
			for(String part : parts) {
				addText(part, color, font);
			}
		} else {
			GUISource.setTextColor(label, color);
			addFlowWidget(label);
		}
	}
	
	public void addFlowWidget(StandardWidget newWidget) {
		widgets.push(newWidget);
		addWidget(newWidget);
		newWidget.setWidth(width);
		updateFlowContent();
	}
	
	public void removeFlowWidget(StandardWidget widget) {
		widgets.remove(widget);
		removeWidget(widget);
		updateFlowContent();
	}
	
	protected void updateFlowContent() {
		int start = (up ? 0 : widgets.size() - 1);
		
		for(int i = start; getLoopCondition(i); i += (up ? 1 : -1)) {
			StandardWidget widget = widgets.get(i);
			int y = widgetHeight * i;
			if(!up) y = height - (widgetHeight * (i+1));
			widget.setY(y);
		}
		layout();
	}
	
	protected boolean getLoopCondition(int i) {
		if(up) return i < widgets.size();
		return i >= 0;
	}
	
	public void clearAllWidgets() {
		Collection<StandardWidget> copy = new ArrayList<StandardWidget>(widgets);
		for(StandardWidget w : copy) {
			removeFlowWidget(w);
		}
		copy.clear();
	}
	
	public LinkedList<StandardWidget> getFlowWidgets() { return widgets; }
	
	public int getWidgetHeight() { return widgetHeight; }
}